filenameBase = 'screenCapture';
fileExtension = '.gif';
filename = [filenameBase,fileExtension];
filenameMangling = 0;
while(exist(filename,'file'))
    filename = [filenameBase,'_',num2str(filenameMangling),fileExtension];
    filenameMangling = filenameMangling + 1;
end
pos = get(0, 'screensize');
robot = java.awt.Robot();
rect = java.awt.Rectangle(pos(1),pos(2),pos(3),pos(4));
for n = 1:30
    pause(1/100);
    cap = robot.createScreenCapture(rect);
    rgb = typecast(cap.getRGB(0,0,cap.getWidth,cap.getHeight,[],0,cap.getWidth),'uint8');
    imgData = zeros(cap.getHeight,cap.getWidth,3,'uint8');
    imgData(:,:,1) = reshape(rgb(3:4:end),cap.getWidth,[])';
    imgData(:,:,2) = reshape(rgb(2:4:end),cap.getWidth,[])';
    imgData(:,:,3) = reshape(rgb(1:4:end),cap.getWidth,[])';
    [imind,cm] = rgb2ind(imgData,256); 
    if n == 1 
      imwrite(imind,cm,filename,'gif', 'Loopcount',inf); 
    else 
      imwrite(imind,cm,filename,'gif','WriteMode','append'); 
    end 
end
fclose all;

